package app.framework.freemarker.loader;

import app.framework.freemarker.util.EcmaScriptUtil;
import cn.hutool.core.io.IoUtil;
import freemarker.cache.TemplateLoader;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

/**
 * <p>
 * 自定义模板加载器，添加针对 JS 脚本的特殊处理逻辑。
 * </p>
 *
 * @author mh.z
 */
public class AppTemplateLoader implements TemplateLoader {
    private TemplateLoader targetLoader;

    private static final String JS_SUFFIX = ".js";

    public AppTemplateLoader(TemplateLoader targetLoader) {
        this.targetLoader = targetLoader;
    }

    @Override
    public Object findTemplateSource(String name) throws IOException {
        return targetLoader.findTemplateSource(name);
    }

    @Override
    public long getLastModified(Object templateSource) {
        return targetLoader.getLastModified(templateSource);
    }

    @Override
    public Reader getReader(Object templateSource, String encoding) throws IOException {
        Reader reader = targetLoader.getReader(templateSource, encoding);
        String path = templateSource.toString();

        if (!path.endsWith(JS_SUFFIX)) {
            return reader;
        }

        String sourceContent = IoUtil.read(reader, true);
        // 计算源代码的开始和结束索引
        int startIndex = EcmaScriptUtil.getSourceStartIndex(sourceContent);
        int endIndex = EcmaScriptUtil.getSourceEndIndex(sourceContent);
        // 生成目标内容
        String targetContent = sourceContent.substring(startIndex, endIndex);

        return new StringReader(targetContent);
    }

    @Override
    public void closeTemplateSource(Object templateSource) throws IOException {
        targetLoader.closeTemplateSource(templateSource);
    }

}
